package com.zhh.front.controller;

import com.zhh.api.model.BidInfo;
import com.zhh.api.model.RechargeRecord;
import com.zhh.api.model.User;
import com.zhh.api.service.InvestService;
import com.zhh.common.contants.RedisKey;
import com.zhh.common.util.CommonUtil;
import com.zhh.front.view.RankView;
import com.zhh.front.view.RespResult;
import com.zhh.front.view.center.IncomeResultView;
import com.zhh.front.view.center.InvestResultView;
import com.zhh.front.view.center.RechargeResultView;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

@Api(tags = "投资理财产品")
@RestController
@RequestMapping("/v1/invest")
public class InvestController extends BaseController{

    //投资排行榜
    @ApiOperation(value = "投资排行榜", notes = "显式投资金额最高的3位用户信息")
    @GetMapping("/rank")
    public RespResult showInvestRank(){

        //把redis中前三条的数据取出来
        Set<ZSetOperations.TypedTuple<String>> redisTemplates = stringRedisTemplate
                .boundZSetOps(RedisKey.KEY_INVEST_RANK).reverseRangeWithScores(0,2);

        //把取出来的ZSet集合数据放到List集合中
        List<RankView> rankList = new ArrayList<>();
        //遍历set集合
        redisTemplates.forEach(tuple -> {
            //tuple.getValue(); 手机号
            //tuple.getScore(); 投资金额
            rankList.add(new RankView(CommonUtil.tuoMinPhone(tuple.getValue()), tuple.getScore()));
        });
        //返回给前端
        RespResult result = RespResult.ok();
        result.setList(rankList);
        return result;
    }


    //获取用户和资金信息
    @ApiOperation(value = "获取投资信息")
    @GetMapping("/records")
    public RespResult queryInvestPage(@RequestHeader("uid") Integer uid,
                                      @RequestParam(required = false,defaultValue = "1") Integer pageNo,
                                      @RequestParam(required = false,defaultValue = "6") Integer pageSize){
        RespResult result = RespResult.fail();

        //数据验证
        if(uid != null && uid > 0) {
            //数据库中取出充值记录
            List<BidInfo> records = investService.queryByUid(uid,pageNo,pageSize);
            //成功
            result = RespResult.ok();
            //把RechargeRecord类转换成RechargeResultView视图类
            result.setList(toView(records));
        }
        return result;
    }


    private List<InvestResultView> toView(List<BidInfo> src){
        List<InvestResultView> target = new ArrayList<>();
        src.forEach( record -> {
            target.add( new InvestResultView(record.getId(),
                    productService.queryTypeById(record.getLoanId()),
                    record.getBidMoney(),
                    record.getBidTime()));
        });
        return target;
    }

    //购买理财产品
    @ApiOperation(value = "投资理财产品")
    @PostMapping("/product")
    public RespResult investProduct(@RequestHeader("uid") Integer uid,
                                    @RequestParam("productId") Integer productId,
                                    @RequestParam("money") BigDecimal money){
        RespResult result = RespResult.fail();
        if( (uid != null && uid > 0) && (productId != null && productId > 0) &&( money != null && money.intValue() % 100 == 0 && money.intValue() >= 100)){
           int investResult = investService.investProduct(uid,productId,money);
            switch (investResult){
                case 0:
                    result.setMsg("投资数据不正确");
                    break;
                case 1:
                    result = RespResult.ok();
                    modifyInvestRank(uid,money);
                    break;
                case 2:
                    result.setMsg("资金账号不存在");
                    break;
                case 3:
                    result.setMsg("账户资金不足");
                    break;
                case 4:
                    result.setMsg("理财产品不存在");
                    break;
                case 5:
                    result.setMsg("剩余金额不足");
                    break;
            }
        }
        return result;
    }

    /*更新投资排行榜*/
    private void modifyInvestRank(Integer uid,BigDecimal money){
        User user  = userService.queryById(uid);
        if(user != null){
            //更新redis中的投资排行榜
            String key = RedisKey.KEY_INVEST_RANK;
            //incrementScore()用户金额累加
            stringRedisTemplate.boundZSetOps(key).incrementScore(user.getPhone(),money.doubleValue());
        }
    }
}
